package com.xielx.httpclikent.bean;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public abstract class MyHttpRequest implements Serializable {
    private int readTimeout = 30000;
    private int connectTimeout = 30000;
    private String url;
    private Map<String,String> header = new HashMap<>();
    private Map<String,String> params = new HashMap<>();

    public MyHttpRequest(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Map<String, String> getParams() {
        return params;
    }

    public void setParams(Map<String, String> params) {
        this.params = params;
    }

    public MyHttpRequest addParam(String name, String value){
        params.put(name,value);
        return this;
    }

    public Map<String, String> getHeader() {
        return header;
    }

    public void setHeader(Map<String, String> header) {
        this.header = header;
    }

    public void addHeader(String name,String value){
        this.header.put(name,value);
    }

    public abstract boolean isPost();

    public abstract String getMethod();

    public URL toURL() throws UnsupportedEncodingException, MalformedURLException {
        StringBuilder sb = new StringBuilder(url);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(url.indexOf("?")<0?"?":"&");
            sb.append(entry.getKey()).append("=");
            sb.append(URLEncoder.encode(entry.getValue(),"UTF-8"));
        }
        return new URL(sb.toString());
    }

    public int getReadTimeout() {
        return readTimeout;
    }

    public void setReadTimeout(int readTimeout) {
        this.readTimeout = readTimeout;
    }

    public int getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }


}
